<?php

class importSmartPostDataTask extends sfBaseTask
{
  protected function configure()
  {
    // // add your own arguments here
    // $this->addArguments(array(
    //   new sfCommandArgument('my_arg', sfCommandArgument::REQUIRED, 'My argument'),
    // ));

    $this->addOptions(array(
      new sfCommandOption('application', null, sfCommandOption::PARAMETER_REQUIRED, 'The application name'),
      new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
      new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
      // add your own options here
    ));

    $this->namespace        = '';
    $this->name             = 'importSmartPostData';
    $this->briefDescription = '';
    $this->detailedDescription = <<<EOF
The [importSmartPostData|INFO] task does things.
Call it with:

  [php symfony importSmartPostData|INFO]
EOF;
  }

  protected function execute($arguments = array(), $options = array())
  {
    // initialize the database connection
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

    $xml = $this->getSmartPostData();
    $typeId = $this->getTransportType('SmartPost');

    foreach ($xml[0] as $entity)
    {
        $region = str_replace('Tallinn/', '', $entity->group_name);
        $name = $region.','.$entity->city.','.$entity->address;
        
        $zoneName['Translation'] = array('et' => array('name' => $name), 'en' => array ('name' => $name));
        $zone = new ShippingZone();
        $zone->fromArray($zoneName);
        $zone->save();
    
        $zvt = new ShippingZoneVsTransportType();
        $zvt->setTypeId($typeId);
        $zvt->setZoneId($zone->getId());
        $zvt->save();
    }     
  }

  protected function getTransportType($name)
  {
    $type = Doctrine_Query::create()
                ->from('TransportType t')
                ->innerJoin('t.Translation tt')
                ->where('tt.name = ?', $name)
                ->fetchArray();
    return $type[0]['id'];
  }

  protected function getSmartPostData()
  {
    $xml = simplexml_load_file('http://smartpost.ee/places.xml');
    return $xml;
  }
}